package com.gzkemays.demo.config.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gzkemays
 * @date 2021/3/18 16:31
 */
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
  private AuthenticationManager authenticationManager;

  public JwtLoginFilter(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
    // 放行接口
    super.setFilterProcessesUrl("/login");
  }

  // 登录成功操作，生成 token 加入响应头部
  @Override
  protected void successfulAuthentication(
      HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain,
      Authentication authResult)
      throws IOException {
    //    AuthUser user = (AuthUser) authResult.getPrincipal();
    //
    //    String token =
    //        jwt.generateJsonWebToken(user.getAuthorities(), user.getId(), user.getUsername());
    //    response.addHeader("token", token);
    //    response.setCharacterEncoding("utf-8"); // 设置 HttpServletResponse使用utf-8编码
    //    response.setHeader("Content-Type", "application/json; charset=utf-8"); // 设置响应头的编码
    JSONObject json = new JSONObject();
    json.put("code", 200);
    json.put("msg", "登录成功！");

    response.getWriter().write(json.toString());
  }
}
